package com.zx.tradeclient.ctrl.index1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.URLHelper;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.entity.NewsInfo;

public class NewsFragment extends Fragment {
	private static final String KEY = "key";
	private NewsListAdapter newsListAdapter;
	private LoadMoreListViewWithProgress listViewForNews;
	private ArrayList<NewsInfo> listDataForNews;
	private String newsTypeId;
	private ImageLoader imageLoader;
	private TopHead head;
	private int page = 1, totalPage = 1;
	private TradeApp app;

	public static Fragment instance(Navigation navigation) {
		NewsFragment fragment = new NewsFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable(KEY, navigation);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		listDataForNews = new ArrayList<NewsInfo>();
		imageLoader = ((TradeApp) (getActivity().getApplicationContext())).imageLoader;
		newsTypeId = ((Navigation) getArguments().getSerializable(KEY)).getId();
		head = new TopHead(getActivity());

		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.news_main, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		app = (TradeApp) getActivity().getApplication();
		listViewForNews = (LoadMoreListViewWithProgress) getActivity()
				.findViewById(R.id.news_list);
		newsListAdapter = new NewsListAdapter(getActivity(), listDataForNews);
			View headview = getActivity().getLayoutInflater().inflate(
					R.layout.news_top, null);
			head.init(headview);
			listViewForNews.getListView().addHeaderView(headview);
		

		listViewForNews.getListView().setAdapter(newsListAdapter);
		listViewForNews.getListView().setOnItemClickListener(
				new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent,
							final View view, int position, long id) {

						Intent intent = new Intent(NewsFragment.this
								.getActivity(), DetailActivity.class);
						intent.putExtra("newsId",
								"" + listDataForNews.get(position - 1).getId());
						startActivity(intent);
					}
				});
		listViewForNews.getListView().setOnLoadMoreListener(
				new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {
						page++;
						newsListTask(newsTypeId);
					}
				});

		if (listDataForNews.size() == 0) {
			newsListTask(newsTypeId);
		} else {
			newsListAdapter.notifyDataSetChanged();
			listViewForNews.show();
			if (page == totalPage) {
				listViewForNews.getListView().loadComplete(false);
			}
		}

	}

	@Override
	public void onStart() {
		head.onStart();
		super.onStart();
	}

	@Override
	public void onStop() {
		head.onStop();
		super.onStop();
	}

	// NewsListAdapter
	private class ViewHolder {
		public ImageView img;
		public TextView title;
		public TextView content;
	}

	private class NewsListAdapter extends BaseAdapter {

		private List<NewsInfo> topics;
		private LayoutInflater mlinflater;

		public NewsListAdapter(Context context, List<NewsInfo> list) {
			this.mlinflater = LayoutInflater.from(context);
			this.topics = list;
		}

		@Override
		public int getCount() {
			return topics.size();
		}

		@Override
		public Object getItem(int position) {
			return Integer.valueOf(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup viewGroup) {
			final NewsInfo topic = topics.get(position);
			if (view == null) {
				view = mlinflater.inflate(R.layout.news_list_item, null);
				ViewHolder vh = new ViewHolder();
				vh.title = (TextView) view
						.findViewById(R.id.news_textview_title);
				vh.content = (TextView) view
						.findViewById(R.id.news_textview_content);
				vh.img = (ImageView) view.findViewById(R.id.news_img_img);
				view.setTag(vh);
			}

			ViewHolder holder = (ViewHolder) view.getTag();
			imageLoader.DisplayImage(
					URLHelper.mPrefixImg + "/" + topic.getImgPath(),
					holder.img, R.drawable.default_small);
			holder.title.setText(topic.getTitle());
			holder.img.setScaleType(ScaleType.CENTER_CROP);
			holder.content.setText(topic.getIntro());
			if (Constant.debug)
				Log.d("href", URLHelper.mPrefixImg + topic.getImgPath());

			return view;
		}
	}

	// 网络请求
	private void newsListTask(String typeId) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "newList");
		map.put("typeId", typeId);
		map.put("currentPage", "" + page);
		map.put("rowCountPerPage", "5");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				if (response != null) {
					parseJson(response);
				}
			}

			@Override
			public void onFailure(Throwable e) {

			}
		});
	}

	// 分析JSON数据
	private void parseJson(JSONObject response) {
		try {
			String currentPage = response.getString("currentPage");
			String totalPage = response.getString("totalPage");
			this.totalPage = Integer.parseInt(totalPage);
			if (currentPage.equals(totalPage)) {
				listViewForNews.getListView().loadComplete(false);
			}

			String datalist = response.getString("dataList");
			JSONArray dataListList = new JSONArray(datalist);
			for (int i = 0; i < dataListList.length(); i++) {
				NewsInfo one = new NewsInfo();
				JSONObject news = dataListList.getJSONObject(i);
				one.setId(news.getString("id"));
				one.setTitle(news.getString("title"));
				one.setIntro(news.getString("intro"));
				one.setImgPath(news.getString("imgPath"));
				listDataForNews.add(one);
			}

			if (page == 1) {
				String slidedata = response.getString("slideData");
				JSONArray slideDataList = new JSONArray(slidedata);
				for (int i = 0; i < slideDataList.length(); i++) {
					final JSONObject pic = slideDataList.getJSONObject(i);
					Map<String, String> map = new HashMap<String, String>();
					map.put("imgPath", pic.getString("imgPath"));
					map.put("title", pic.getString("title"));
					map.put("id", pic.getString("id"));
					head.listData.add(map);
				}
				if(slideDataList.length()==0){
					
				}else{
				head.onUpdate();
				}
			}

			newsListAdapter.notifyDataSetChanged();
			listViewForNews.show();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
